package util;

import zach.parser.ParseError;

public final class Util {
	/**
	 * 将一个Interger数组转化为一个int数组
	 * 
	 * @param integerArray
	 * @return
	 */
	public static int[] integersArrayToIntArray( Integer[] integerArray ) {
		int len = integerArray.length;
		int[] temp = new int[len];
		for ( int i = 0; i != len; i++ ) {
			temp[i] = integerArray[i];
		}
		return temp;
	}

	/**
	 * 制作一个Ascii表,一个Ascii表是一个boolean[128]
	 * <p>
	 * 例子:AsciiMap( " \n\t" ); // 空白符表
	 * </p>
	 * 
	 * @param str
	 *            Ascii表支持字符组成的字符串
	 * @return Ascii表
	 * 
	 */
	public static boolean[] AsciiMap( String str ) {
		boolean[] retVal = new boolean[128];
		for ( int i = 0, len = str.length(); i != len; ++i ) {
			assert str.charAt( i ) < 128 : "Asciimaps only receives ascii char"; // 确保字符串中只有ascii字符
			retVal[str.charAt( i )] = true; // 设置对于位置为true
		}
		return retVal;
	}

	// 最基本的StringReader,主要用于测试
	public static class BasicStringReader implements StringReader {
		String str;
		int pos;

		public BasicStringReader( String str ) {
			this.str = str;
			this.pos = 0;
		}

		@Override
		public int cur() {
			return pos == str.length() ? -1 : str.charAt( this.pos );
		}

		@Override
		public void eat() throws ZachError {
			if ( pos == str.length() ) throw new ZachError( ParseError.UnexpectedEOF );
			++pos;
		}
	}

	/**
	 * 转换一个unicode整数数组为字符串
	 * <p>
	 * 例子:IntArrayToString( new Integer[] { 0x41, 0x42, 0x43 } ); // 返回"ABC"
	 * </p>
	 * 
	 * @param intArray
	 *            unicode整数数组
	 * @return 对应的字符串
	 */
	public static String intArrayToString( Integer[] intArray ) {
		StringBuilder stringBuilder = new StringBuilder();
		for ( int x : intArray ) {
			stringBuilder.append( ( char ) x );
		}
		return stringBuilder.toString();
	}

	public static String toString( char c ) {
		return java.lang.Character.toString( c );
	}
}
